import React, { useState } from 'react';
import { 
  SyncOutlined, 
  EyeOutlined, 
  CopyOutlined,
  DownOutlined,
  RightOutlined,
  DatabaseOutlined
} from '@ant-design/icons';
import { Tooltip, Tag } from 'antd';
import StatusBadge from '../common/StatusBadge';
import { CopyToClipboard } from 'react-copy-to-clipboard';

const TaskTable = ({ 
  tasks = [], 
  loading = false,
  onRunTask,
  onViewDetails,
  runningTasks = new Set(),
  dataSourceTypes = [], 
  getDbTypeName,
  erModels = []
}) => {
  const [expandedTasks, setExpandedTasks] = useState(new Set());
   const toggleTaskExpand = (taskId) => {
       setExpandedTasks(prev => {
         const newSet = new Set(prev);
         if (newSet.has(taskId)) {
           newSet.delete(taskId);
         } else {
           newSet.add(taskId);
         }
         return newSet;
       });
     };
    
  
  // 获取关联的ER模型
  const getErModelsForTask = (taskId) => {
    return erModels.filter(er => er.source_id === taskId);
  };

  // 获取数据库类型名称
  const getDbTypeNameSafe = (typeId) => {
    return getDbTypeName ? getDbTypeName(typeId) : '未知类型';
  };

  // 复制任务ID
  const handleCopyTaskId = (taskId) => {
    // 显示复制成功提示
    console.log(`已复制任务ID: ${taskId}`);
  };

  if (loading) {
    return (
      <div className="card task-table">
        <h2 className="card-title">任务探查列表</h2>
        <div className="loading-placeholder">
          <SyncOutlined spin style={{ fontSize: 24, marginRight: 10 }} />
          加载任务数据中...
        </div>
      </div>
    );
  }

  if (!tasks || tasks.length === 0) {
    return (
      <div className="card task-table">
        <h2 className="card-title">任务探查列表</h2>
        <div className="empty-state">
          <div className="empty-icon">📭📭</div>
          <p>暂无任务数据</p>
          <p className="hint">请先添加数据源并创建ER模型</p>
        </div>
      </div>
    );
  }

  return (
    <div className="card task-table">
      <h2 className="card-title">任务探查列表</h2>
      
      <div className="table-container">
        <table>
          <thead>
            <tr>
              <th style={{ width: '30px' }}></th>
              <th>数据源名称</th>
              <th>数据库类型</th>
              <th>数据库名称</th>
              <th>Host</th>
              <th>Port</th>
              <th>er模型名称</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {tasks.map(task => {
              const isRunning = runningTasks.has(task.id);
              const isExpanded = expandedTasks.has(task.id);
              const taskErModels = getErModelsForTask(task.id);
              const taskId = task.task_id || task.id; // 使用task_id作为任务ID
              
              return (
                <React.Fragment key={task.id}>
                  <tr data-task-id={taskId}> {/* 隐藏列存储taskId */}
                    <td>
                      {taskErModels.length > 0 && (
                        <button 
                          className="expand-btn"
                          onClick={() => toggleTaskExpand(task.id)}
                        >
                          {isExpanded ? <DownOutlined /> : <RightOutlined />}
                        </button>
                      )}
                    </td>
                    <td>{task.name}</td>
                    <td>
                      <Tag color="blue">
                        {getDbTypeNameSafe(task.type_id)}
                      </Tag>
                    </td>
                    <td>{task.database}</td>
                    <td>{task.host}</td>
                    <td>{task.port}</td>
                    <td>{task.er_name}</td>
                    <td>
                      <StatusBadge 
                        status={task.status} 
                        taskId={taskId} // 传递taskId
                      />
                    </td>
                    <td>
                      <div className="actions">
                        <Tooltip title="复制任务ID">
                          <CopyToClipboard 
                            text={taskId} 
                            onCopy={() => handleCopyTaskId(taskId)}
                          >
                            <button className="btn-icon">
                              <CopyOutlined />
                            </button>
                          </CopyToClipboard>
                        </Tooltip>
                        
                        {task.status === 'completed' ? (
                          <button 
                            className="btn-primary" 
                            onClick={() => onViewDetails(taskId)} // 使用taskId
                          >
                            <EyeOutlined /> 查看详情
                          </button>
                        ) : (
                          <button 
                            className="btn-primary" 
                            onClick={() => onRunTask(taskId)} // 使用taskId
                            disabled={isRunning}
                          >
                            
                            {isRunning ? 
                              
                              <><SyncOutlined spin /> 执行中</> : '执行探查'
                            }
                          </button>
                          
                        )}
                      </div>
                    </td>
                  </tr>
                  
                  {isExpanded && taskErModels.length > 0 && (
                    <tr className="er-models-row">
                      <td colSpan="9">
                        <div className="er-models-container">
                          <div className="er-models-header">
                            <DatabaseOutlined style={{ marginRight: 8 }} />
                            <span>关联ER模型</span>
                          </div>
                          <div className="er-models-list">
                            {taskErModels.map(erModel => (
                              <div key={erModel.id} className="er-model-item">
                                <div className="er-model-name">
                                  {erModel.name}
                                </div>
                                <div className="er-model-type">
                                  <Tag color="geekblue">
                                    {erModel.config_type}
                                  </Tag>
                                </div>
                                <div className="er-model-scope">
                                  <Tag color="purple">
                                    {erModel.scope}
                                  </Tag>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default TaskTable;